﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;
using Common;
using Common.Config;
using Common.Model;
using ConsoleService.API;
using ConsoleService.Model;
using HtmlAgilityPack;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Web;
using Quartz;


namespace ConsoleService.Job
{
    /// <summary>
    /// 同步数据，并实现Excute方法
    /// </summary>
    public class SynchronousDataJob : IJob
    {
        Logger logger = LogManager.GetCurrentClassLogger();
        public SynchronousDataJob()
        {
            NLog.Web.NLogBuilder.ConfigureNLog("nlog.config");
        }

        public Task Execute(IJobExecutionContext context)
        {
            return Task.Run(() =>
            {
                Stopwatch s = new Stopwatch();
                s.Start();

                UserAPI api = new UserAPI();
                var currentUser = api.GetUserToken();

                CommonAPI commonAPI = new CommonAPI();
                var result = commonAPI.GetOilPrice3(currentUser.data.Token);
                if (result)
                {
                    var msg = $"同步油价数据成功用时：{ s.Elapsed.ToString()}" + DateTime.Now.ToString();
                    api.WrittenQueue(msg, currentUser.data.Token);

                    api.WrittenQueue(new DelayMessageModel
                    {
                        CallBackUrl = $"{Configs.WebUrl}api/Common/GetCurrentOil",
                        JsonData = "",
                        DelayTime = 10 * 60 * 1000,
                    }); ;



                    s.Stop();
                    logger.Warn(msg);
                    Console.WriteLine(msg);
                }
                else
                {
                    logger.Warn("油价同步异常，通过redis订阅方式进行，重试！");
                    //如果油价没有获取到，通过redis订阅方式进行，重试
                    api.RedisPublish(new RedisPublishModel()
                    {
                        Token = currentUser.data.Token,
                        Channel = "GetOil",
                        Msg = "远程服务器重试！",
                    });
                }
            });
        }
    }
}
